<?php
namespace Common\Model;
use Think\Model\RelationModel;

/**
 * Base Model Class
 *
 * @package Common\Model
 * @author lythesia
**/
class BaseModel extends RelationModel {
// {{{ Dynamic hack relation operation functions
  
  /* All attribute value MUST BE string! */

  /**
   * Set requested relation fields
   *
   * @param  string relation name
   * @param  string fields(with ',' separate)
   * @return Model $this
   * @author lythesia
   **/
  public function setRelField($name, $field) {
    if(!empty($this->_link)) {
      $this->_link[$name]['mapping_fields'] = $field;
    }
    return $this;
  }


  /**
   * Set requested relation fields
   *
   * @param  string relation name
   * @param  string fields(with ',' separate)
   * @return Model $this
   * @author lythesia
   **/
  public function setRelOrder($name, $order) {
    if(!empty($this->_link)) {
      $this->_link[$name]['mapping_order'] = $order;
    }
    return $this;
  }


  /**
   * Set requested relation condtions
   *
   * @param  string relation name
   * @param  string conditions(sql *HACK* allowed)
   * @return Model $this
   * @author lythesia
   **/
  public function setRelCond($name, $cond) {
    if(!empty($this->_link)) {
      $this->_link[$name]['condition'] = $cond;
    }
    return $this;
  }


  /**
   * Set requested relation limit
   *
   * @param  string relation name
   * @param  string|int limit number
   * @return Model $this
   * @author lythesia
   **/
  public function setRelLimit($name, $limit) {
    if(!empty($this->_link)) {
      $this->_link[$name]['mapping_limit'] = $limit;
    }
    return $this;
  }


  /**
   * Set requested relation(as general method)
   *
   * @param  string relation name
   * @param  array attribute setter of (`key => value`) or pure array
   * @return Model $this
   * @author lythesia
   **/
  public function setRelation($name, $setter) {
    if(!empty($this->_link)) {
      $array = array();
      foreach($setter as $_key => $_val) {
        if(!is_numeric($_key)) {
          $array[$_key] = $_val;
        }
        else {
          $array[$_val] = $setter[$_key+1]; 
          break;
        }
      }
      $_rel = & $this->_link[$name];
      foreach($array as $_key => $_val) {
        $_rel[$_key] = $_val;
      }
    }
    return $this;
  }
}
// }}}
